/*
 * The MIT License
 *
 * Copyright 2011 Edwin Bratini <edwin.bratini@gmail.com>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*
 * RegistroEdicionEstudiante.java
 *
 * Created on Nov 10, 2011, 10:08:24 AM
 */
package org.salvador_dali.psychsys.ui;

import java.awt.Color;
import java.awt.Toolkit;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import org.salvador_dali.psychsys.business.exceptions.PreexistingEntityException;
import org.salvador_dali.psychsys.business.validators.DateFieldValidator;
import org.salvador_dali.psychsys.business.DateUtils;
import org.salvador_dali.psychsys.business.validators.EmptyFieldValidator;
import org.salvador_dali.psychsys.business.EntitySearcher;
import org.salvador_dali.psychsys.business.validators.FieldValidator;
import org.salvador_dali.psychsys.business.validators.FormFieldValidator;
import org.salvador_dali.psychsys.business.jpa_controllers.EstudianteJpaDao;
import org.salvador_dali.psychsys.business.jpa_controllers.TutorJpaDao;
import org.salvador_dali.psychsys.business.jpa_controllers.TutorEstudianteJpaDao;
import org.salvador_dali.psychsys.business.validators.PhoneFieldValidator;
import org.salvador_dali.psychsys.model.EstudianteDao;
import org.salvador_dali.psychsys.model.TutorEstudianteDao;
import org.salvador_dali.psychsys.model.entities.Estudiante;
import org.salvador_dali.psychsys.model.entities.Tutor;
import org.salvador_dali.psychsys.model.entities.TutorEstudiante;
import org.salvador_dali.psychsys.model.entities.TutorEstudiantePK;

/**
 *
 * @author Edwin Bratini <edwin.bratini@gmail.com>
 */
public class RegistroEdicionEstudiante extends javax.swing.JFrame {

    private RegistroEdicionModo modo = RegistroEdicionModo.REGISTRO;
    private Estudiante estAEditar;
    private Map<Integer, Tutor> tutores = new HashMap<Integer, Tutor>();
    private Map<Integer, TutorEstudiante> tutoresEstudiantes = new HashMap<Integer, TutorEstudiante>();
    private Map<Integer, String> tutEstOpAccion = new HashMap<Integer, String>();

    /** Creates new form RegistroEdicionEstudiante */
    public RegistroEdicionEstudiante() {
        initComponents();


    }

    public RegistroEdicionEstudiante(RegistroEdicionModo modo) {
        this();
        this.modo = modo;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        ppmTutores = new javax.swing.JPopupMenu();
        mniNuevoTutor = new javax.swing.JMenuItem();
        mniEditarRelFamiliar = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        mniRemoverTutor = new javax.swing.JMenuItem();
        jPanel1 = new javax.swing.JPanel();
        pnlInfoPersonal = new javax.swing.JPanel();
        lblDni = new javax.swing.JLabel();
        txtDni = new javax.swing.JTextField();
        lblTipoDni = new javax.swing.JLabel();
        cmbTipoDni = new javax.swing.JComboBox();
        lblPrimerNombre = new javax.swing.JLabel();
        txtPrimerNombre = new javax.swing.JTextField();
        lblSegundoNombre = new javax.swing.JLabel();
        txtSegundoNombre = new javax.swing.JTextField();
        lblPrimerApellido = new javax.swing.JLabel();
        txtPrimerApellido = new javax.swing.JTextField();
        lblSegundoApellido = new javax.swing.JLabel();
        txtSegundoApellido = new javax.swing.JTextField();
        lblNacionalidad = new javax.swing.JLabel();
        txtNacionalidad = new javax.swing.JTextField();
        lblGenero = new javax.swing.JLabel();
        cmbGenero = new javax.swing.JComboBox();
        lblDniValMarker = new javax.swing.JLabel();
        lblPrimerNombreValMarker = new javax.swing.JLabel();
        lblPrimerApellidoValMarker = new javax.swing.JLabel();
        lblSegApellidoValMarker = new javax.swing.JLabel();
        lblNacionalidadValMarker = new javax.swing.JLabel();
        lblApodo = new javax.swing.JLabel();
        txtApodo = new javax.swing.JTextField();
        lblFechaNacimiento = new javax.swing.JLabel();
        ftfFechaNacimiento = new javax.swing.JFormattedTextField();
        lblLugarNacimiento = new javax.swing.JLabel();
        txtLugarNacimiento = new javax.swing.JTextField();
        lblHermanos = new javax.swing.JLabel();
        spnHermanos = new javax.swing.JSpinner();
        lblLugarEntreHermanos = new javax.swing.JLabel();
        spnLugarEntreHermanos = new javax.swing.JSpinner();
        lblPeso = new javax.swing.JLabel();
        lblTalla = new javax.swing.JLabel();
        lblFechaNacimientoValMarker = new javax.swing.JLabel();
        lblLugarNacimientoValMarker = new javax.swing.JLabel();
        lblTallaValMarker = new javax.swing.JLabel();
        lblPesoValMarker = new javax.swing.JLabel();
        lblCursoActual = new javax.swing.JLabel();
        cmbGradoEscolar = new javax.swing.JComboBox();
        cmbNivelEscolar = new javax.swing.JComboBox();
        txtEscuelaProcedencia = new javax.swing.JTextField();
        lblEscuelaProcedencia = new javax.swing.JLabel();
        ftfTalla = new javax.swing.JFormattedTextField();
        ftfPeso = new javax.swing.JFormattedTextField();
        pnlInfoContacto = new javax.swing.JPanel();
        lblTelefono = new javax.swing.JLabel();
        lblDireccion = new javax.swing.JLabel();
        lblTelValMarker = new javax.swing.JLabel();
        ftfTelefono = new javax.swing.JFormattedTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        txaDireccion = new javax.swing.JTextArea();
        lblDirValMarker = new javax.swing.JLabel();
        pnlTutores = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblTutores = new javax.swing.JTable();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        mniNuevoTutor.setText("Nuevo Tutor");
        mniNuevoTutor.setToolTipText("Click para agregar tutor");
        mniNuevoTutor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniNuevoTutorActionPerformed(evt);
            }
        });
        ppmTutores.add(mniNuevoTutor);

        mniEditarRelFamiliar.setText("Editar Relacion Familiar");
        mniEditarRelFamiliar.setToolTipText("Click para editar relacion familiar entre tutor y estudiante");
        mniEditarRelFamiliar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniEditarRelFamiliarActionPerformed(evt);
            }
        });
        ppmTutores.add(mniEditarRelFamiliar);
        ppmTutores.add(jSeparator1);

        mniRemoverTutor.setText("Remover Tutor");
        mniRemoverTutor.setToolTipText("Click para remover tutor");
        mniRemoverTutor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniRemoverTutorActionPerformed(evt);
            }
        });
        ppmTutores.add(mniRemoverTutor);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Registrar Estudiante");
        setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/resources/images/psych logo.png")));
        setResizable(false);
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                formMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                formMouseReleased(evt);
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        pnlInfoPersonal.setBorder(javax.swing.BorderFactory.createTitledBorder("Informacion Personal"));

        lblDni.setText("DNI");

        txtDni.setNextFocusableComponent(cmbTipoDni);

        lblTipoDni.setText("Tipo DNI");

        cmbTipoDni.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Cedula", "Pasaporte", "NSS" }));
        cmbTipoDni.setNextFocusableComponent(txtPrimerNombre);

        lblPrimerNombre.setText("Primer Nombre");

        txtPrimerNombre.setNextFocusableComponent(txtSegundoNombre);

        lblSegundoNombre.setText("Segundo Nombre");

        txtSegundoNombre.setNextFocusableComponent(txtPrimerApellido);

        lblPrimerApellido.setText("Primer Apellido");

        txtPrimerApellido.setNextFocusableComponent(txtSegundoApellido);

        lblSegundoApellido.setText("Segundo Apellido");

        txtSegundoApellido.setNextFocusableComponent(txtApodo);

        lblNacionalidad.setText("Nacionalidad");

        txtNacionalidad.setNextFocusableComponent(cmbGenero);

        lblGenero.setText("Genero");

        cmbGenero.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Masculino", "Femenino" }));
        cmbGenero.setNextFocusableComponent(ftfFechaNacimiento);

        lblDniValMarker.setForeground(new java.awt.Color(255, 51, 51));
        lblDniValMarker.setLabelFor(txtDni);

        lblPrimerNombreValMarker.setForeground(new java.awt.Color(255, 51, 51));
        lblPrimerNombreValMarker.setLabelFor(txtPrimerNombre);

        lblPrimerApellidoValMarker.setForeground(new java.awt.Color(255, 51, 51));
        lblPrimerApellidoValMarker.setLabelFor(txtPrimerApellido);

        lblSegApellidoValMarker.setForeground(new java.awt.Color(255, 51, 51));
        lblSegApellidoValMarker.setLabelFor(txtSegundoApellido);

        lblNacionalidadValMarker.setForeground(new java.awt.Color(255, 51, 51));
        lblNacionalidadValMarker.setLabelFor(txtNacionalidad);
        lblNacionalidadValMarker.setToolTipText(null);

        lblApodo.setText("Apodo");

        txtApodo.setNextFocusableComponent(txtNacionalidad);

        lblFechaNacimiento.setText("Fecha de Nacimiento");

        try {
            ftfFechaNacimiento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        ftfFechaNacimiento.setNextFocusableComponent(txtLugarNacimiento);

        lblLugarNacimiento.setText("Lugar de Nacimiento");

        txtLugarNacimiento.setNextFocusableComponent(spnHermanos);

        lblHermanos.setText("Hermanos");

        spnHermanos.setModel(new javax.swing.SpinnerNumberModel(0, 0, 100, 1));
        spnHermanos.setNextFocusableComponent(spnLugarEntreHermanos);

        lblLugarEntreHermanos.setText("Lugar Entre Hermanos");

        spnLugarEntreHermanos.setModel(new javax.swing.SpinnerNumberModel(0, 0, 100, 1));
        spnLugarEntreHermanos.setNextFocusableComponent(ftfTalla);

        lblPeso.setText("Peso (kilogramos)");

        lblTalla.setText("Talla (metros)");

        lblFechaNacimientoValMarker.setForeground(new java.awt.Color(255, 51, 51));
        lblFechaNacimientoValMarker.setLabelFor(ftfFechaNacimiento);
        lblFechaNacimientoValMarker.setToolTipText("");

        lblLugarNacimientoValMarker.setForeground(new java.awt.Color(255, 51, 51));
        lblLugarNacimientoValMarker.setLabelFor(txtLugarNacimiento);
        lblLugarNacimientoValMarker.setToolTipText("");

        lblTallaValMarker.setForeground(new java.awt.Color(255, 51, 51));
        lblTallaValMarker.setLabelFor(ftfTalla);
        lblTallaValMarker.setToolTipText("");

        lblPesoValMarker.setForeground(new java.awt.Color(255, 51, 51));
        lblPesoValMarker.setLabelFor(ftfPeso);
        lblPesoValMarker.setToolTipText("");

        lblCursoActual.setText("Curso Actual");

        cmbGradoEscolar.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8" }));
        cmbGradoEscolar.setNextFocusableComponent(cmbNivelEscolar);
        cmbGradoEscolar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbGradoEscolarActionPerformed(evt);
            }
        });

        cmbNivelEscolar.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Basica", "Media", "Pre-Primaria" }));
        cmbNivelEscolar.setNextFocusableComponent(txtEscuelaProcedencia);

        txtEscuelaProcedencia.setNextFocusableComponent(ftfTelefono);

        lblEscuelaProcedencia.setText("Escuela Procedencia");

        ftfTalla.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
        ftfTalla.setNextFocusableComponent(ftfPeso);

        ftfPeso.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
        ftfPeso.setNextFocusableComponent(cmbGradoEscolar);

        javax.swing.GroupLayout pnlInfoPersonalLayout = new javax.swing.GroupLayout(pnlInfoPersonal);
        pnlInfoPersonal.setLayout(pnlInfoPersonalLayout);
        pnlInfoPersonalLayout.setHorizontalGroup(
            pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlInfoPersonalLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblDni)
                    .addComponent(lblTipoDni)
                    .addComponent(lblPrimerNombre)
                    .addComponent(lblSegundoNombre)
                    .addComponent(lblPrimerApellido)
                    .addComponent(lblSegundoApellido)
                    .addComponent(lblApodo)
                    .addComponent(lblNacionalidad)
                    .addComponent(lblGenero))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlInfoPersonalLayout.createSequentialGroup()
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(cmbTipoDni, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnlInfoPersonalLayout.createSequentialGroup()
                                .addComponent(txtDni, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblDniValMarker))
                            .addComponent(txtApodo, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtSegundoApellido, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtPrimerApellido, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE)
                            .addComponent(txtNacionalidad, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtSegundoNombre, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtPrimerNombre, javax.swing.GroupLayout.Alignment.LEADING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblSegApellidoValMarker)
                            .addComponent(lblNacionalidadValMarker)
                            .addComponent(lblPrimerApellidoValMarker)
                            .addComponent(lblPrimerNombreValMarker))
                        .addGap(40, 40, 40)
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblLugarEntreHermanos)
                            .addComponent(lblLugarNacimiento)
                            .addComponent(lblFechaNacimiento)
                            .addComponent(lblHermanos)
                            .addComponent(lblCursoActual)
                            .addComponent(lblEscuelaProcedencia)
                            .addComponent(lblPeso)
                            .addComponent(lblTalla))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(pnlInfoPersonalLayout.createSequentialGroup()
                                .addComponent(cmbGradoEscolar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmbNivelEscolar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(pnlInfoPersonalLayout.createSequentialGroup()
                                .addComponent(ftfFechaNacimiento, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblFechaNacimientoValMarker))
                            .addGroup(pnlInfoPersonalLayout.createSequentialGroup()
                                .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(txtEscuelaProcedencia, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtLugarNacimiento, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblLugarNacimientoValMarker))
                            .addGroup(pnlInfoPersonalLayout.createSequentialGroup()
                                .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(ftfPeso, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE)
                                    .addComponent(ftfTalla))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblTallaValMarker)
                                    .addComponent(lblPesoValMarker)))
                            .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(spnLugarEntreHermanos, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
                                .addComponent(spnHermanos, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 37, Short.MAX_VALUE))))
                    .addComponent(cmbGenero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(74, Short.MAX_VALUE))
        );
        pnlInfoPersonalLayout.setVerticalGroup(
            pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlInfoPersonalLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlInfoPersonalLayout.createSequentialGroup()
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblDni)
                            .addComponent(txtDni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblDniValMarker))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblTipoDni)
                            .addComponent(cmbTipoDni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblPrimerNombre)
                            .addComponent(txtPrimerNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblPrimerNombreValMarker))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblSegundoNombre)
                            .addComponent(txtSegundoNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblPrimerApellido)
                            .addComponent(txtPrimerApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblPrimerApellidoValMarker))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblSegundoApellido)
                            .addComponent(txtSegundoApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblSegApellidoValMarker))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblApodo)
                            .addComponent(txtApodo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(pnlInfoPersonalLayout.createSequentialGroup()
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(ftfFechaNacimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblFechaNacimiento)
                            .addComponent(lblFechaNacimientoValMarker))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtLugarNacimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblLugarNacimiento)
                            .addComponent(lblLugarNacimientoValMarker))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(spnHermanos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblHermanos))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(spnLugarEntreHermanos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblLugarEntreHermanos))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(pnlInfoPersonalLayout.createSequentialGroup()
                                .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(ftfTalla, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lblTalla)
                                    .addComponent(lblTallaValMarker))
                                .addGap(26, 26, 26))
                            .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(ftfPeso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(lblPesoValMarker)
                                .addComponent(lblPeso)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblCursoActual)
                            .addComponent(cmbGradoEscolar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cmbNivelEscolar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlInfoPersonalLayout.createSequentialGroup()
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblNacionalidad)
                            .addComponent(txtNacionalidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblNacionalidadValMarker))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblGenero)
                            .addComponent(cmbGenero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(pnlInfoPersonalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtEscuelaProcedencia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(lblEscuelaProcedencia)))
                .addContainerGap(16, Short.MAX_VALUE))
        );

        pnlInfoContacto.setBorder(javax.swing.BorderFactory.createTitledBorder("Informacion de Contacto"));

        lblTelefono.setText("Telefono");

        lblDireccion.setText("Direccion");

        lblTelValMarker.setForeground(new java.awt.Color(255, 51, 51));
        lblTelValMarker.setLabelFor(ftfTelefono);

        try {
            ftfTelefono.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(###) ###-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        txaDireccion.setColumns(20);
        txaDireccion.setLineWrap(true);
        txaDireccion.setRows(3);
        txaDireccion.setWrapStyleWord(true);
        jScrollPane2.setViewportView(txaDireccion);

        lblDirValMarker.setForeground(new java.awt.Color(255, 51, 51));
        lblDirValMarker.setLabelFor(txaDireccion);

        javax.swing.GroupLayout pnlInfoContactoLayout = new javax.swing.GroupLayout(pnlInfoContacto);
        pnlInfoContacto.setLayout(pnlInfoContactoLayout);
        pnlInfoContactoLayout.setHorizontalGroup(
            pnlInfoContactoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlInfoContactoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlInfoContactoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(pnlInfoContactoLayout.createSequentialGroup()
                        .addComponent(lblTelefono)
                        .addGap(5, 5, 5))
                    .addGroup(pnlInfoContactoLayout.createSequentialGroup()
                        .addComponent(lblDireccion)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(pnlInfoContactoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlInfoContactoLayout.createSequentialGroup()
                        .addComponent(ftfTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblTelValMarker))
                    .addGroup(pnlInfoContactoLayout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblDirValMarker)))
                .addContainerGap())
        );
        pnlInfoContactoLayout.setVerticalGroup(
            pnlInfoContactoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlInfoContactoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlInfoContactoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblTelefono)
                    .addComponent(ftfTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblTelValMarker))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlInfoContactoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblDireccion)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblDirValMarker))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pnlTutores.setBorder(javax.swing.BorderFactory.createTitledBorder("Tutores"));

        tblTutores.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nombre Tutor", "Relacion Familiar"
            }
        ));
        tblTutores.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tblTutoresMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                tblTutoresMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tblTutores);

        javax.swing.GroupLayout pnlTutoresLayout = new javax.swing.GroupLayout(pnlTutores);
        pnlTutores.setLayout(pnlTutoresLayout);
        pnlTutoresLayout.setHorizontalGroup(
            pnlTutoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 384, Short.MAX_VALUE)
        );
        pnlTutoresLayout.setVerticalGroup(
            pnlTutoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pnlInfoPersonal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(pnlInfoContacto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(pnlTutores, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlInfoPersonal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pnlInfoContacto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(pnlTutores, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        statusMessageLabel.setForeground(new java.awt.Color(0, 153, 51));
        statusMessageLabel.setText("Estudiante registrado exitosamente.");

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/circle progress bar 20x20.png"))); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 825, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 610, Short.MAX_VALUE)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel))
                .addContainerGap())
        );

        btnAceptar.setText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(659, Short.MAX_VALUE)
                .addComponent(btnAceptar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnCancelar)
                .addContainerGap())
            .addComponent(statusPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private DefaultTableModel getDefTblModel() {
        DefaultTableModel dtm = new DefaultTableModel(null, new Object[]{"Nombre Tutor", "Relacion Familiar"}) {

            @Override
            public boolean isCellEditable(int rowIndex, int mColIndex) {
                return false;
            }
        };

        return dtm;
    }

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        statusMessageLabel.setVisible(false);
        statusAnimationLabel.setVisible(false);

        // customizando el jtable y evitando que puedan mover las columnas
        tblTutores.setColumnModel(new DefaultTableColumnModel() {

            @Override
            public void moveColumn(int columnIndex, int newIndex) {
                if (columnIndex == 1 || newIndex == 1) {
                    return;
                }
                super.moveColumn(columnIndex, newIndex);
            }
        });

        if (modo != null && modo.equals(RegistroEdicionModo.REGISTRO)) {
            tblTutores.setModel(getDefTblModel());
        } else if (modo != null && modo.equals(RegistroEdicionModo.EDICION)){
            if (estAEditar == null) {
                JOptionPane.showMessageDialog(this, "El estudiante a editar no esta establecido", "Editar Estudiante", JOptionPane.ERROR_MESSAGE);
                return;
            }
            List<TutorEstudiante> tutEsts = (List<TutorEstudiante>) new TutorEstudianteJpaDao().getTutorEstudianteByEstId(estAEditar.getEstId());

            // llenando el map y mostrando en jtable
            Object[][] data = new Object[tutEsts.size()][];
            int i = 0;
            for (TutorEstudiante tutEst : tutEsts) {
                tutoresEstudiantes.put(i, tutEst);
                data[i] = new Object[]{String.format("%s %s", tutEst.getTutor().getTutPrimerNombre(), tutEst.getTutor().getTutPrimerApellido()),
                    tutEst.getTesRelacionFamiliar()};
                i++;
            }

            DefaultTableModel dtm = new DefaultTableModel(data, new Object[]{"Nombre Tutor", "Relacion Familiar"});
            tblTutores.setModel(dtm);
            
            //
            txtDni.setText(estAEditar.getEstDni() != null ? estAEditar.getEstDni() : "");
            cmbTipoDni.setSelectedItem(estAEditar.getEstTipoDni() != null ? estAEditar.getEstTipoDni() : "NA");
            txtPrimerNombre.setText(estAEditar.getEstPrimerNombre());
            txtSegundoNombre.setText(estAEditar.getEstSegundoNombre() != null ? estAEditar.getEstSegundoNombre() : "");
            txtPrimerApellido.setText(estAEditar.getEstPrimerApellido());
            txtSegundoApellido.setText(estAEditar.getEstSegundoApellido() != null ? estAEditar.getEstSegundoApellido() : "");
            txtApodo.setText(estAEditar.getEstApodo() != null ? estAEditar.getEstApodo() : "");
            txtNacionalidad.setText(estAEditar.getEstNacionalidad());
            cmbGenero.setSelectedIndex(estAEditar.getEstGenero() == 'M' ? 0 : 1);
            ftfFechaNacimiento.setText(String.format("%1$td%1$tm%1$tY", estAEditar.getEstFechaNacimiento()));
            txtLugarNacimiento.setText(estAEditar.getEstLugarNacimiento());
            spnHermanos.setValue(estAEditar.getEstCantHermanos());
            spnLugarEntreHermanos.setValue(estAEditar.getEstOrdenHermanos());
            ftfTalla.setText(estAEditar.getEstTalla() != null ? estAEditar.getEstTalla().toString() : "");
            ftfPeso.setText(estAEditar.getEstPeso() != null ? estAEditar.getEstPeso().toString() : "");
            cmbGradoEscolar.setSelectedItem(estAEditar.getEstGradoEscolar());
            cmbNivelEscolar.setSelectedItem(estAEditar.getEstNivelEscolar());
            txtEscuelaProcedencia.setText(estAEditar.getEstEscuelaProcedencia() != null ? estAEditar.getEstEscuelaProcedencia() : "");
            ftfTelefono.setText(estAEditar.getEstTelefono() != null ? estAEditar.getEstTelefono() : "");
            txaDireccion.setText(estAEditar.getEstDireccion());
            
        }
    }//GEN-LAST:event_formWindowOpened

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        // TODO add your handling code here:
        // TODO: implementar correctamente el spinning progress bar
        ProgressCircle pc = new ProgressCircle(statusAnimationLabel);
        String trabajoCompletoMensaje = "Estudiante registrado exitosamente.";
        pc.start();
        LimpiadorComponentes.limpiarValidationMarkers(this);

        if (!checkFormFields()) {
            statusMessageLabel.setText("Por favor corriga los campos marcados.");
            statusMessageLabel.setForeground(Color.red);
            new Thread(new LabelToolTipShower(statusMessageLabel, 3000)).start();
            return;
        }

        if (tblTutores.getRowCount() < 1) {
            statusMessageLabel.setText("Por favor seleccione al menos un tutor para el estudiante.");
            statusMessageLabel.setForeground(Color.red);
            new Thread(new LabelToolTipShower(statusMessageLabel, 3000)).start();
            return;
        }
        // si todo esta bien
        statusMessageLabel.setVisible(false);

        EstudianteDao estDao = new EstudianteJpaDao();
        if (estDao.getEstudianteByDNI(txtDni.getText()) != null) {
            lblDniValMarker.setVisible(true);
            statusMessageLabel.setText("Ya existe un estudiante con DNI digitado.");
            statusMessageLabel.setForeground(Color.red);
            statusMessageLabel.setVisible(true);
            return;
        }

        Estudiante estudiante = new Estudiante(null, txtPrimerApellido.getText(), txtSegundoApellido.getText(), txtPrimerNombre.getText(), txaDireccion.getText().trim(),
                txtNacionalidad.getText(), cmbGenero.getSelectedItem().toString().charAt(0), DateUtils.parseDate(ftfFechaNacimiento.getText()), txtLugarNacimiento.getText(),
                cmbNivelEscolar.getSelectedItem().toString(), Integer.parseInt(cmbGradoEscolar.getSelectedItem().toString()), Integer.valueOf(spnHermanos.getValue().toString()),
                Integer.valueOf(spnLugarEntreHermanos.getValue().toString()), 'A');

        estudiante.setEstDni((!txtDni.getText().isEmpty() ? txtDni.getText() : null));
        estudiante.setEstTipoDni((!txtDni.getText().isEmpty() ? cmbTipoDni.getSelectedItem().toString() : null));
        estudiante.setEstSegundoNombre((!txtSegundoNombre.getText().isEmpty() ? txtSegundoNombre.getText() : null));
        estudiante.setEstApodo((!txtApodo.getText().isEmpty() ? txtApodo.getText() : null));
        estudiante.setEstTelefono((!ftfTelefono.getText().trim().equalsIgnoreCase("(   )    -") ? extractTelFromFormField(ftfTelefono.getText()) : null));
        estudiante.setEstTalla((!ftfTalla.getText().isEmpty() ? BigDecimal.valueOf(Double.parseDouble(ftfTalla.getText())) : null));
        estudiante.setEstPeso((!ftfPeso.getText().isEmpty() ? BigDecimal.valueOf(Double.parseDouble(ftfPeso.getText())) : null));
        estudiante.setEstEscuelaProcedencia((!txtEscuelaProcedencia.getText().isEmpty() ? txtEscuelaProcedencia.getText() : null));

        //crear el objeto estudianteDao e invocar el metodo persist del mismo     
        if (this.modo.equals(RegistroEdicionModo.REGISTRO)) {
            try {
                estDao.persist(estudiante);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, String.format("<html><p>Error al crear registro de estudiante<br />%s</p></html>",
                        e.getMessage()), "Registrar Estudiante", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // asegurando el estudiante persistido para relacionarlo con sus tutores
            List<Estudiante> estudiantesCheck = (List<Estudiante>) estDao.getEstudiantesByNombreCompleto(txtPrimerNombre.getText(), txtPrimerApellido.getText());

            Estudiante estudianteConfirmado = estudiantesCheck.get(estudiantesCheck.size() - 1);
            //Estudiante estudianteConfirmado = null;
            /*if (estudiantesCheck.size() > 1) {
                estudianteConfirmado = estudiantesCheck.get(estudiantesCheck.size() - 1);
                /*ConfirmarEstudiante ce = new ConfirmarEstudiante(this, true);
                ce.setEstudiantes(estudiantesCheck);
                
                // conseguir estudiante confirmado
                ce.setLocationRelativeTo(this);
                ce.setVisible(true);
                
                if (ce.getEntitySelectedId() != null) {
                    estudianteConfirmado = estDao.findById(ce.getEntitySelectedId());
                }
            } else {
                estudianteConfirmado = (Estudiante) estudiantesCheck.get(0);
            }*/
            
            if (estudianteConfirmado == null) {
                JOptionPane.showMessageDialog(this, "<html><p>Error al crear registro de estudiante<br />El estudiante no esta confirmado</p></html>",
                        "Registrar Estudiante", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // relacionando estudiante con tutores
            for (Map.Entry<Integer, Tutor> tutEntry : tutores.entrySet()) {
                TutorEstudiante tutEst = new TutorEstudiante(new TutorEstudiantePK(tutEntry.getValue().getTutId(), estudianteConfirmado.getEstId()));
                tutEst.setTesRelacionFamiliar(tblTutores.getValueAt(tutEntry.getKey(), 1).toString());
                estudiante.getTutorEstudianteCollection().add(tutEst);

                try {
                    new TutorEstudianteJpaDao().persist(tutEst);
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this, String.format("<html><p>Error al crear registro de estudiante<br />%s</p></html>",
                            e.getMessage()), "Registrar Estudiante", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
        } else {
            // TODO: ver como implementar lo de tutores (adicion, remocion)
            if (estAEditar != null) {
                estudiante.setEstId(estAEditar.getEstId());
                estDao.update(estudiante);
                trabajoCompletoMensaje = trabajoCompletoMensaje.replace("registrado", "editado");
            } else {
                statusMessageLabel.setText("Error al editar estudiante, favor cierre y vuelva a intentarlo.");
                statusMessageLabel.setForeground(Color.red);
                return;
            }
        }

        statusMessageLabel.setText(trabajoCompletoMensaje);
        statusMessageLabel.setForeground(Color.GREEN);
        statusMessageLabel.setVisible(true);
        new Thread(new LabelToolTipShower(statusMessageLabel, 3500)).start();
        LimpiadorComponentes.limpiarComponentes(this);
        spnHermanos.setValue(0);
        spnLugarEntreHermanos.setValue(0);
        tblTutores.setModel(getDefTblModel());
        tutores.clear();
        txtDni.requestFocusInWindow();
        pc.stop();
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void formMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMousePressed
        // TODO add your handling code here:
        if (evt.isPopupTrigger()) {
            ppmTutores.getComponent(1).setEnabled(false);
            ppmTutores.getComponent(3).setEnabled(false);
            ppmTutores.show(evt.getComponent(), evt.getX(), evt.getY());
        }
    }//GEN-LAST:event_formMousePressed

    private void formMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseReleased
        // TODO add your handling code here:
        if (evt.isPopupTrigger()) {
            ppmTutores.getComponent(1).setEnabled(false);
            ppmTutores.getComponent(3).setEnabled(false);
            ppmTutores.show(evt.getComponent(), evt.getX(), evt.getY());
        }
    }//GEN-LAST:event_formMouseReleased

    private void tblTutoresMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblTutoresMousePressed
        // TODO add your handling code here:
        if (evt.isPopupTrigger()) {
            if (tblTutores.getSelectedRowCount() == 0) {
                ppmTutores.getComponent(1).setEnabled(false);
                ppmTutores.getComponent(3).setEnabled(false);
            } else if (tblTutores.getSelectedRowCount() == 1) {
                ppmTutores.getComponent(1).setEnabled(true);
                ppmTutores.getComponent(3).setEnabled(true);
            } else if (tblTutores.getSelectedRowCount() > 1) {
                ppmTutores.getComponent(1).setEnabled(false);
                ppmTutores.getComponent(3).setEnabled(true);
            }
            ppmTutores.show(evt.getComponent(), evt.getX(), evt.getY());
        }
    }//GEN-LAST:event_tblTutoresMousePressed

    private void tblTutoresMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblTutoresMouseReleased
        // TODO add your handling code here:
        if (evt.isPopupTrigger()) {
            if (tblTutores.getSelectedRowCount() == 0) {
                ppmTutores.getComponent(1).setEnabled(false);
                ppmTutores.getComponent(3).setEnabled(false);
            } else if (tblTutores.getSelectedRowCount() == 1) {
                ppmTutores.getComponent(1).setEnabled(true);
                ppmTutores.getComponent(3).setEnabled(true);
            } else if (tblTutores.getSelectedRowCount() > 1) {
                ppmTutores.getComponent(1).setEnabled(false);
                ppmTutores.getComponent(3).setEnabled(true);
            }
            ppmTutores.show(evt.getComponent(), evt.getX(), evt.getY());
        }
    }//GEN-LAST:event_tblTutoresMouseReleased

    private void mniNuevoTutorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniNuevoTutorActionPerformed
        // TODO add your handling code here:
        BusquedaRapida brt = new BusquedaRapida(this, true);
        brt.setTitle("Buscar Tutor");
        brt.setEntitySearcher(new org.salvador_dali.psychsys.ui.EntitySearcher.TutorSearcher());
        brt.getLblEntidades().setText("Tutores");
        brt.setLocationRelativeTo(this);
        brt.setVisible(true);

        Object tutId = brt.getEntitySelectedId();
        if (tutId != null) {
            Tutor tut = new TutorJpaDao().findById(tutId);
            if ((modo.equals(RegistroEdicionModo.REGISTRO) && tutores.containsValue(tut))
                    || (modo.equals(RegistroEdicionModo.EDICION) && tutoresEstudiantes.containsValue(new TutorEstudiante(tut.getTutId(), estAEditar.getEstId())))) {
                JOptionPane.showMessageDialog(this, "Este tutor ya aparece listado", "Agregar Tutor", JOptionPane.ERROR_MESSAGE);
                return;
            }
            String relFamiliar = JOptionPane.showInputDialog(this, "Relacion Familiar", "Relacion Familiar Tutor-Estudiante", JOptionPane.QUESTION_MESSAGE);
            //Tutor tut = new TutorJpaDao().findById(tutId);
            DefaultTableModel dtm = (DefaultTableModel) tblTutores.getModel();
            dtm.addRow(new Object[]{tut.toString(), relFamiliar});
            //if (modo.equals(RegistroEdicionModo.REGISTRO)) {
            tutores.put((dtm.getRowCount() - 1), tut);
            //} else {
            //tutoresEstudiantes.put((dtm.getRowCount() - 1), new TutorEstudiante(tut.getTutId(), estAEditar.getEstId()));
            //}
        }
    }//GEN-LAST:event_mniNuevoTutorActionPerformed

    private void mniEditarRelFamiliarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniEditarRelFamiliarActionPerformed
        // TODO add your handling code here:
        if (modo.equals(RegistroEdicionModo.REGISTRO)) {
            int rowEditing = tblTutores.getSelectedRow();
            String oldRelFam = tblTutores.getValueAt(rowEditing, 1) != null ? tblTutores.getValueAt(rowEditing, 1).toString() : "";
            String nuevoRelFamiliar = JOptionPane.showInputDialog(this, "Relacion Familiar", tblTutores.getValueAt(rowEditing, 1));
            if (nuevoRelFamiliar == null || (nuevoRelFamiliar != null && nuevoRelFamiliar.isEmpty())) {
                nuevoRelFamiliar = oldRelFam;
            }
            tblTutores.setValueAt(nuevoRelFamiliar, rowEditing, 1);
        } else {
        }
    }//GEN-LAST:event_mniEditarRelFamiliarActionPerformed

    private void mniRemoverTutorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniRemoverTutorActionPerformed
        // TODO add your handling code here:
        // TODO: revisar cuando se seleccionar filas que no son continuas o que no empiezan desde el principio
        int[] rowsDeleting = tblTutores.getSelectedRows();
        int selectedRow = -1;
        DefaultTableModel dtm = (DefaultTableModel) tblTutores.getModel();
        for (int i = 0; i < rowsDeleting.length; i++) {
            selectedRow = tblTutores.getSelectedRow();
            dtm.removeRow(selectedRow);
            if (modo.equals(RegistroEdicionModo.REGISTRO) || (modo.equals(RegistroEdicionModo.EDICION) && tutores.containsKey(i))) {
                tutores.remove(selectedRow);
            } else {
                if (!tutores.containsKey(i)) {
                    tutEstOpAccion.put(i, "remover");
                }
            }
        }
    }//GEN-LAST:event_mniRemoverTutorActionPerformed

    private void cmbGradoEscolarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbGradoEscolarActionPerformed
        // TODO add your handling code here:
        int gradoEscolar = Integer.parseInt(cmbGradoEscolar.getSelectedItem().toString());
        if (gradoEscolar >= 5) {
            cmbNivelEscolar.setModel(new DefaultComboBoxModel(new String[] {"Basica"}));
        } else if (gradoEscolar >= 2) {
            cmbNivelEscolar.setModel(new DefaultComboBoxModel(new String[] {"Basica", "Media"}));
        } else if (gradoEscolar >= 1) {
            cmbNivelEscolar.setModel(new DefaultComboBoxModel(new String[] {"Basica", "Inicial", "Media"}));
        }
    }//GEN-LAST:event_cmbGradoEscolarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(RegistroEdicionEstudiante.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(RegistroEdicionEstudiante.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(RegistroEdicionEstudiante.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(RegistroEdicionEstudiante.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new RegistroEdicionEstudiante().setVisible(true);
            }
        });
    }

    public Estudiante getEstAEditar() {
        return estAEditar;
    }

    public void setEstAEditar(Estudiante estAEditar) {
        this.estAEditar = estAEditar;
    }

    public RegistroEdicionModo getModo() {
        return modo;
    }

    public void setModo(RegistroEdicionModo modo) {
        this.modo = modo;
    }

    private boolean checkFormFields() {
        boolean validFields = true;

        FieldValidator emptynessVal, phoneVal, dateVal;
        emptynessVal = new EmptyFieldValidator();
        phoneVal = new PhoneFieldValidator("\\(\\d\\d\\d\\) \\d\\d\\d-\\d\\d\\d\\d");
        dateVal = new DateFieldValidator("\\d\\d-\\d\\d-\\d\\d\\d\\d");

        FieldValidator[] emptynessArr = new FieldValidator[]{emptynessVal};

        HashMap<JLabel, FieldValidator[]> campos = new HashMap<JLabel, FieldValidator[]>();

        // validando info personal
        campos.put(lblPrimerNombreValMarker, emptynessArr);
        campos.put(lblPrimerApellidoValMarker, emptynessArr);
        campos.put(lblSegApellidoValMarker, emptynessArr);
        campos.put(lblNacionalidadValMarker, emptynessArr);

        if (!ftfFechaNacimiento.getText().trim().equalsIgnoreCase("-  -")) {
            campos.put(lblFechaNacimientoValMarker, new FieldValidator[]{emptynessVal, dateVal});
        } else {
            lblFechaNacimientoValMarker.setToolTipText("El campo no puede estar vacio");
            lblFechaNacimientoValMarker.setVisible(true);
            validFields &= false;
        }

        campos.put(lblLugarNacimientoValMarker, emptynessArr);

        // validando info contacto
        if (!ftfTelefono.getText().trim().equalsIgnoreCase("(   )    -")) {
            campos.put(lblTelValMarker, new FieldValidator[]{emptynessVal, phoneVal});
        } else {
            lblTelValMarker.setToolTipText("El campo no puede estar vacio");
            lblTelValMarker.setText("*");
            lblTelValMarker.setVisible(true);
            validFields &= false;
        }

        campos.put(lblDirValMarker, emptynessArr);

        validFields = FormFieldValidator.verifyFormFields(campos);

        return validFields;
    }

    private String extractTelFromFormField(String tel) {
        return tel.replaceAll("-", "").replace("(", "").replace(")", "").replace(" ", "");
    }

    private void removerTutor(int tutRow) {
        TutorEstudianteDao tutEstDao = new TutorEstudianteJpaDao();
        TutorEstudiante tutEst = tutEstDao.getTutorEstudiante(tutores.get(tutRow), estAEditar);
        tutEstDao.remove(tutEst);
    }

    private void agregarTutor() {
        Tutor tutAgregar = tutores.get(tutores.size() - 1);
        try {
            new TutorEstudianteJpaDao().persist(new TutorEstudiante(new TutorEstudiantePK(tutAgregar.getTutId(), estAEditar.getEstId())));
        } catch (PreexistingEntityException ex) {
            Logger.getLogger(RegistroEdicionEstudiante.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(RegistroEdicionEstudiante.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void removerTutores() {
        for (Map.Entry tutEntry : tutores.entrySet()) {
            removerTutor((Integer) tutEntry.getKey());
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JComboBox cmbGenero;
    private javax.swing.JComboBox cmbGradoEscolar;
    private javax.swing.JComboBox cmbNivelEscolar;
    private javax.swing.JComboBox cmbTipoDni;
    private javax.swing.JFormattedTextField ftfFechaNacimiento;
    private javax.swing.JFormattedTextField ftfPeso;
    private javax.swing.JFormattedTextField ftfTalla;
    private javax.swing.JFormattedTextField ftfTelefono;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JLabel lblApodo;
    private javax.swing.JLabel lblCursoActual;
    private javax.swing.JLabel lblDirValMarker;
    private javax.swing.JLabel lblDireccion;
    private javax.swing.JLabel lblDni;
    private javax.swing.JLabel lblDniValMarker;
    private javax.swing.JLabel lblEscuelaProcedencia;
    private javax.swing.JLabel lblFechaNacimiento;
    private javax.swing.JLabel lblFechaNacimientoValMarker;
    private javax.swing.JLabel lblGenero;
    private javax.swing.JLabel lblHermanos;
    private javax.swing.JLabel lblLugarEntreHermanos;
    private javax.swing.JLabel lblLugarNacimiento;
    private javax.swing.JLabel lblLugarNacimientoValMarker;
    private javax.swing.JLabel lblNacionalidad;
    private javax.swing.JLabel lblNacionalidadValMarker;
    private javax.swing.JLabel lblPeso;
    private javax.swing.JLabel lblPesoValMarker;
    private javax.swing.JLabel lblPrimerApellido;
    private javax.swing.JLabel lblPrimerApellidoValMarker;
    private javax.swing.JLabel lblPrimerNombre;
    private javax.swing.JLabel lblPrimerNombreValMarker;
    private javax.swing.JLabel lblSegApellidoValMarker;
    private javax.swing.JLabel lblSegundoApellido;
    private javax.swing.JLabel lblSegundoNombre;
    private javax.swing.JLabel lblTalla;
    private javax.swing.JLabel lblTallaValMarker;
    private javax.swing.JLabel lblTelValMarker;
    private javax.swing.JLabel lblTelefono;
    private javax.swing.JLabel lblTipoDni;
    private javax.swing.JMenuItem mniEditarRelFamiliar;
    private javax.swing.JMenuItem mniNuevoTutor;
    private javax.swing.JMenuItem mniRemoverTutor;
    private javax.swing.JPanel pnlInfoContacto;
    private javax.swing.JPanel pnlInfoPersonal;
    private javax.swing.JPanel pnlTutores;
    private javax.swing.JPopupMenu ppmTutores;
    private javax.swing.JSpinner spnHermanos;
    private javax.swing.JSpinner spnLugarEntreHermanos;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JTable tblTutores;
    private javax.swing.JTextArea txaDireccion;
    private javax.swing.JTextField txtApodo;
    private javax.swing.JTextField txtDni;
    private javax.swing.JTextField txtEscuelaProcedencia;
    private javax.swing.JTextField txtLugarNacimiento;
    private javax.swing.JTextField txtNacionalidad;
    private javax.swing.JTextField txtPrimerApellido;
    private javax.swing.JTextField txtPrimerNombre;
    private javax.swing.JTextField txtSegundoApellido;
    private javax.swing.JTextField txtSegundoNombre;
    // End of variables declaration//GEN-END:variables
}
